package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.MyAJAX;
import cn.wolfcode.qo.NoticeQueryObject;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.util.UserContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {


    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private INoticeService noticeService;

    @RequestMapping("/empLogin")
    @ResponseBody
    public MyAJAX login(String username, String password, HttpSession session, NoticeQueryObject qo) {
        Employee loginEmployee = employeeService.login(username, password);
        //session.setAttribute("USER_IN_SESSION",loginEmployee);
        //用工具类代替
        UserContextUtil.setUserContext(loginEmployee);
        //如果不是超管就把权限给查出来,便于权限同行
        if (!loginEmployee.isAdmin()) {
            //通过员工ID查出这个员工所含有的权限表达式
            List<String> expressions = employeeService.selectByPermission(loginEmployee.getId());
            //把个这个表达式传进session,目的是能让拦截器取到这个权限
            //session.setAttribute("EXPRESSION_IN_SESSION",expressions);
            //用工具类代替
            UserContextUtil.setPermission(expressions);
        }
        //查询出这个用户已读的公告
        noticeService.noticeHin(qo);
        return new MyAJAX();
    }

    @RequestMapping("/empLogout")
    public String logOut(HttpSession session) {
        //删除session中的所有map
        session.invalidate();
        return "redirect:/login.html";
    }

    @RequestMapping("/alterPassword")
    @ResponseBody
    public MyAJAX alterPassword(HttpSession session, String oldPassword, String newPassword, Long id) {
        //进入更改密码操作
        employeeService.alterPassword(oldPassword, newPassword, id);
        //修改了密码之后推出登录
        session.invalidate();
        return new MyAJAX();
    }

    //跳转到修改密码页面
    @RequestMapping("/password")
    public String inputPassword() {
        return "/employee/password";
    }

    //跳转到没有权限页面
    @RequestMapping("/noPermission")
    public String noPermission() {
        return "/common/noPermission";
    }


}
